package com.qx.cn.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.InterceptorRefs;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.fastjson.JSONObject;
import com.qx.cn.model.Menu;
import com.qx.cn.model.RoleMenu;
import com.qx.cn.model.User;
import com.qx.cn.model.UserRole;
import com.qx.cn.service.MenuService;
import com.qx.cn.service.RoleMenuService;
import com.qx.cn.service.UserRoleService;
import com.qx.cn.service.UserService;
import com.qx.cn.tool.MD5;
import com.qx.cn.tool.ReDupList;
import com.qx.cn.tool.SessionListener;

@ParentPackage("netxzt")
@Namespace("/")
@InterceptorRefs({@InterceptorRef("content")})
@Results({@Result(name = "pageOut", location = "/pageout.jsp"), @Result(name = "pageotherlogin", location = "/pageotherlogin.jsp"),
    @Result(name = "loginout", location = "/admin!loginForm", type = "redirect"), @Result(name = "loginForm", location = "/WEB-INF/page/admin/login.jsp"),
    @Result(name = "alrLogin", location = "/admin!loginForm", type = "redirect")})
@Action("admin")
public class AdminAction extends BaseAction
{
    /**
     * 注释内容
     */
    private static final long serialVersionUID = -7813772643148644628L;
    
    @Autowired
    private UserRoleService userRoleService;
    
    @Autowired
    private RoleMenuService roleMenuService;
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private MenuService menuService;
    
    private String userAccount;
    
    private String pwd;
    
    public String loginForm()
    {
        User user = (User)request.getSession().getAttribute("user");
        if (user != null)
        {
            return "alrLogin";
        }
        return "loginForm";
    }
    
    /**
     * 用户登录
     * 
     * @return
     * @see [类、类#方法、类#成员]
     */
    public String login()
    {
        JSONObject object = new JSONObject();
        User user = userService.loadAdminByPwdAndAccount(userAccount, MD5.toMD5(pwd));
        if (user != null)
        {
            HttpSession session = request.getSession();
            session.setAttribute("user", user);
            SessionListener.isAlreadyEnter(session, user.getUserId());
            
            Set<String> menuSet = new TreeSet<>();
            List<UserRole> userRoles = userRoleService.queryRolesByUserId(user.getUserId());
            List<String> list = new ArrayList<>();
            for (UserRole userRole : userRoles)
            {
                list.add(String.valueOf(userRole.getRoleId()));
            }
            List<String> list2 = ReDupList.removeDuplicate(list);
            for (String roleStr : list2)
            {
                List<RoleMenu> roleMenus = roleMenuService.queryRoleMenusById(roleStr);
                for (RoleMenu roleMenu : roleMenus)
                {
                    Menu menu = menuService.loadMenuByCode(roleMenu.getMenuId());
                    if (menu != null && StringUtils.isNotEmpty(menu.getMenuURL()))
                    {
                        menuSet.add(menu.getMenuURL());
                    }
                }
            }
            
            // 保存当前用户已分配菜单URL
            session.setAttribute("menuset", menuSet);
            
            // 构造返回的json数据
            if (!menuSet.isEmpty())
            {
                object.put("result", 1);
            }
            else
            {
                object.put("result", 2);
                object.put("msg", "该用户还没有访问权限!");
            }
        }
        else
        {
            object.put("result", 2);
            object.put("msg", "登陆失败,用户账号或者密码不正确!");
        }
        
        try
        {
            PrintWriter out = response.getWriter();
            out.print(object.toString());
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        return null;
    }
    
    public String loginout()
    {
        request.getSession().removeAttribute("user");
        return "loginout";
    }
    
    public String appLogin()
    {
        JSONObject object = new JSONObject();
        User user = userService.loadAdminByPwdAndAccount(userAccount, MD5.toMD5(pwd));
        if (user != null)
        {
            request.getSession().setAttribute("user", user);
            object.put("result", 1);
            object.put("msg", "");
        }
        else
        {
            object.put("result", 2);
            object.put("msg", "用户账号或密码错误!");
        }
        try
        {
            PrintWriter out = response.getWriter();
            out.print(object.toString());
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        return null;
    }
    
    public String loseSession()
    {
        return "pageOut";
    }
    
    public String otherlogin()
    {
        return "pageotherlogin";
    }
    
    public String getUserAccount()
    {
        return userAccount;
    }
    
    public void setUserAccount(String userAccount)
    {
        this.userAccount = userAccount;
    }
    
    public String getPwd()
    {
        return pwd;
    }
    
    public void setPwd(String pwd)
    {
        this.pwd = pwd;
    }
}